var app = getApp();
var api = require('../../api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    key_name: '',
    show_goods: false,
    search_focus: false,
    history: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getSearchKeyHistory()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var page = this
    var user = wx.getStorageSync('user_info');
    return {
      path: '/pages/index/index?pid=' + user.user_id,
    }
  },

  //绑定输入
  inputKey: function(e) {

    this.setData({
      search_focus: true,
      key_name: e.detail.value,
      show_goods: false,
    });
    
  },
  //搜索
  search: function() {
    var page = this;
    wx.showLoading({
      title: '加载中',
    })

    if (wx.getStorageSync('shopsearchkey')) {
      var searchkey = wx.getStorageSync('shopsearchkey');
      if (searchkey.indexOf(page.data.key_name) == -1) {
        searchkey.push(page.data.key_name);
        wx.setStorageSync('videosearchkey', searchkey)
      } 
    } else {
      wx.setStorageSync('shopsearchkey', [page.data.key_name])
    }
    page.getSearchKeyHistory()
    app.request({
      url: api.shop.search,
      method: 'POST',
      data: {
        key: page.data.key_name
      },
      success: function(res) {
        if (res.errcode == 0) {
          page.setData({
            goods: res.data,
            show_goods: true,
          })

        }
      },
      fail: function(res) {
        wx.showModal({
          title: '警告',
          content: res.errmsg,
          showCancel: false
        })
      },
      complete: function() {
        wx.hideLoading();
      }
    });
  },
  //搜索历史
  getSearchKeyHistory: function() {
    var searchkey = wx.getStorageSync('shopsearchkey');
    this.setData({
      history: searchkey,
    })
  },
  keysearch: function(e) {
    var page = this
    page.setData({
      key_name: e.currentTarget.dataset.name
    })
    page.search()
  },
  delhistory:function(){
    wx.removeStorage({
      key: 'shopsearchkey',
      success(res) {
        console.log(res.data)
      }
    })
    this.setData({
      history: [],
    })
  }
})